package account

import (
	"context"
	"fmt"
	"math"
	"strings"

	"googee/common/utils"
	"googee/service/account/rpc/account"
	"googee/service/admin/api/internal/svc"
	"googee/service/admin/api/internal/types"

	"github.com/zeromicro/go-zero/core/logx"
)

type AccountLogLogic struct {
	logx.Logger
	ctx    context.Context
	svcCtx *svc.ServiceContext
}

func NewAccountLogLogic(ctx context.Context, svcCtx *svc.ServiceContext) *AccountLogLogic {
	return &AccountLogLogic{
		Logger: logx.WithContext(ctx),
		ctx:    ctx,
		svcCtx: svcCtx,
	}
}

func (l *AccountLogLogic) AccountLog(req *types.AccountLogReq) (*types.AccountLogResp, error) {
	result, err := l.svcCtx.Account.GetAccountLog(l.ctx, &account.AccountLogRequest{
		UserId:  req.Id,
		Current: req.Current,
		Page:    req.PageSize,
	})

	if err != nil {
		return &types.AccountLogResp{
			Current:  req.Current,
			PageSize: req.PageSize,
			Success:  false,
			Code:     "500000",
			Message:  "查询账户记录失败",
		}, nil
	}

	resp := &types.AccountLogResp{}
	utils.MyCopier(&resp.Data, result.Logs)

	result1, err := l.svcCtx.Account.GetPrecision(l.ctx, &account.Empty{})

	if err != nil {
		return nil, err
	}

	m := make(map[string]uint64)
	for k, v := range result1.Precision {
		m[strings.ToLower(k)] = v
	}

	logx.Infof("==========> Account precision: %v", result1.Precision)
	for i, v := range resp.Data {
		if v1, ok := m[v.Name]; ok {
			if v1 >= 1 {
				x := int64(math.Pow10(int(v1)))
				temp := result.Logs[i]
				logx.Infof("========> x=%v", x)
				resp.Data[i].Amount = fmt.Sprintf("%v", float32(temp.Amount)/float32(x))
			}
		}
	}

	resp.Current = req.Current
	resp.Message = "查询成功"
	resp.Success = true
	resp.Code = "000000"
	resp.PageSize = req.PageSize
	resp.Total = result.Total

	return resp, nil
}
